package com.accp.restaurant.service;

import com.accp.restaurant.dao.OrderdishesDao;
import com.accp.restaurant.entity.Dishes;
import com.accp.restaurant.entity.Orderdishes;
import com.accp.restaurant.entity.Room;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderdishesService {


    @Autowired
    private OrderdishesDao orderdishesDao;


    @Cacheable(value = "orderDishes",key = "#roomid")
    public List<Orderdishes> GetOrderdishesByRoomId(int roomid){
        List<Orderdishes> list=orderdishesDao.findByRoom_Roomid(roomid);
        return list;
    }


    @CachePut(value = "Room",key = "#result[0].room.roomid")
    @Transactional
    public List<Orderdishes> UpdateOrderdishes(Long dishesId,String type,Long roomId){
       Orderdishes orderdishes=new Orderdishes();
       orderdishes=orderdishesDao.findByRoom_RoomidAndDishes_Dishesid(roomId,dishesId);
        long count=0;
        List<Orderdishes> list=new ArrayList<Orderdishes>();
       if(orderdishes!=null){
          count=orderdishes.getDishesnum();
           System.out.println(orderdishes.getDishesnum());
       }
       if(type.equals("jia")){
            orderdishes.setDishesnum(count+1);
           orderdishes.setTotalamount(orderdishes.getDishes().getDiscount()*orderdishes.getDishes().getDishesprice());
       }else if(type.equals("jian")){
           if(orderdishes.getDishesnum()==1){
            orderdishesDao.deleteByDishes_Dishesid(dishesId);
            return list =orderdishesDao.findByRoom_Roomid(roomId);
           }else{
               orderdishes.setDishesnum(count-1);
               orderdishes.setTotalamount(orderdishes.getDishes().getDiscount()*orderdishes.getDishes().getDishesprice());
           }
           orderdishes.getDishes().setDiscount(count-1);
           orderdishes.setTotalamount(orderdishes.getDishes().getDiscount()*orderdishes.getDishes().getDishesprice());
       }else if(type.equals("create")&&orderdishes==null){
           orderdishes=new Orderdishes();
           Room room=new Room();
           room.setRoomid(roomId);
           Dishes dishes=new Dishes();
           dishes.setDishesid(dishesId);
           orderdishes.setDishesnum(1);
           orderdishes.setRoom(room);
           orderdishes.setDishes(dishes);
           SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
           orderdishes.setDishestime(simpleDateFormat.format(new Date()));
       }
       orderdishesDao.save(orderdishes);
        list=orderdishesDao.findByRoom_Roomid(roomId);
       return list;
    }


}
